// pages/book-detail/book-detail.js
import {BookModel}  from "../../models/Book.js";
import {LikeModel}  from "../../models/Like.js";
const bookModel = new BookModel();
const likeMode = new LikeModel();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    comments:[],
    book:null,
    likeStatus:false,
    likeCount:0,
    posting:false,
    currentTag:"",
    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title:"加载中",
      mask:true,
    });
    const book_id = options.book_id;
    const detail = bookModel.getBookDetail(book_id);
    const comments = bookModel.getBookComment(book_id);
    const likeStatus = bookModel.getBookFavorStatus(book_id);
    
    Promise.all([detail,comments,likeStatus])
    .then((res)=>{
      // console.log(res);
      this.setData({
        book:res[0],
        comments:res[1].comments,
        likeStatus:res[2].like_status,
        likeCount:res[2].fav_nums
      });
      //隐藏加载框
      wx.hideLoading();
    });
  },

  onLike: function(event){
    let likeOrCanecel = event.detail.behavior;
    likeMode.like(likeOrCanecel, this.data.book.id, 400);
  },
  onFakePost: function(){
    this.setData({
      posting:true,
    });
  },
  onCancel: function(){
    this.setData({
      posting:false,
    });
  },
  onConfirm:function(){
    //新增短评
    let book_id = this.data.book.id;
    let comment = this.data.currentTag;
    if(!comment){
      wx.showToast({
        title:"请填写短评",
        icon:"none",
      });
      return;
    }
    bookModel.postComment(book_id , comment)
    .then(res=>{
      wx.showToast({
        title:"评论成功",
        icon:"none",
      });
      this._refreshComments(book_id);
    });
    this.onCancel();

  },
  onTapClick: function(event){
    this.setData({
      currentTag:event.detail.text,
    });
    
  },

  _refreshComments(book_id){
    const comments = bookModel.getBookComment(book_id);
    comments.then(res=>{
      this.setData({
        comments:res.comments,
      });
    });
  }
})